package js.web.center.netty.code;

import java.util.List;

import org.apache.log4j.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import js.web.center.netty.config.JsWebSocketConstant;
import js.web.center.netty.entity.JsWebSocketBaseProtocol;
/**
 * socket解码器
 * @author qpduw
 *
 */
public class JsWebSocketDecoder extends ByteToMessageDecoder {
	private static Logger logger=Logger.getLogger(JsWebSocketDecoder.class);
	public final static int BASE_LENGTH=8;
	@Override
	protected void decode(ChannelHandlerContext channel, ByteBuf buf, List<Object> out) throws Exception {
		if(buf.readableBytes()>BASE_LENGTH){
			if(buf.readableBytes()>JsWebSocketConstant.socketMaxLength){
				buf.skipBytes(buf.readableBytes());
			}
			int beginReader;
			while(true){
				beginReader=buf.readerIndex();
				buf.markReaderIndex();
				if(buf.readInt()==JsWebSocketConstant.HEAD_DATA){
					break;
				}
				buf.resetReaderIndex();
				buf.readByte();
				if(buf.readableBytes()<BASE_LENGTH){
					return;
				}
			}
			int length=buf.readInt();
			if(buf.readableBytes()<length){
				buf.readerIndex(beginReader);
				return;
			}
			byte[] data=new byte[length];
			buf.readBytes(data);
			JsWebSocketBaseProtocol baseProtocol=new JsWebSocketBaseProtocol(data.length, data);
			out.add(baseProtocol);
		}else{
			channel.close();
			logger.debug("错误的数据结构");
		}
	}
}
